package com.cqb.cn.controller;

import com.google.gson.*;
import com.cqb.cn.common.Exception.MyException;
import com.cqb.cn.common.Exception.ResultEnum;
import com.cqb.cn.common.Exception.ResultUtil;
import com.cqb.cn.common.api.BaseResponse;
import com.cqb.cn.mapper.CourseMapper;
import com.cqb.cn.modle.po.Course;
import com.cqb.cn.modle.po.Person;
import com.cqb.cn.service.DemoService;
import com.sargeraswang.util.ExcelUtil.ExcelLogs;
import com.sargeraswang.util.ExcelUtil.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Desccription: 用于测试框架基础功能
 * create by cqb on 2020/7/4 20:56
 */
@Slf4j
@RestController
@RequestMapping("cc")
public class DemoController {
    @Resource
    private DemoService demoService;
    @Resource
    private CourseMapper courseMapper;

    @GetMapping("/test")
    public String HelloWorld() {
        return "hello-world";
    }


    @GetMapping("CourseList")
    public BaseResponse<List<Course>> getCourseList() {
        List<Course> list = demoService.getCourseList();
        return new BaseResponse<>(true, "获取列表成功", list);
    }

    @RequestMapping("login")
    public BaseResponse login(String username, String password) {
        log.info(username + "," + password);
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
            throw new MyException(ResultEnum.ParamException);
        else {
            Map<String, String> map = new HashMap<>();
            map.put("username", username);
            map.put("password", password);
            return ResultUtil.getSuccess(map);
        }

    }
    /**
     * 描述：下载外部案件导入模板
     *
     * @throws Exception
     */
    @GetMapping(value = "/downloadExcel")
    public void downloadExcel(HttpServletResponse res, HttpServletRequest req) throws Exception {

        String fileName = "test" + ".xlsx";
        ServletOutputStream out;
        res.setContentType("multipart/form-data");
        res.setCharacterEncoding("UTF-8");
        res.setContentType("text/html");
        String filePath = getClass().getResource("/template/" + fileName).getPath();
        String userAgent = req.getHeader("User-Agent");
        if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
        } else {
            // 非IE浏览器的处理：
            fileName = new String((fileName).getBytes("UTF-8"), "ISO-8859-1");
        }
        filePath = URLDecoder.decode(filePath, "UTF-8");
        res.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        FileInputStream inputStream = new FileInputStream(filePath);
        out = res.getOutputStream();
        int b = 0;
        byte[] buffer = new byte[1024];
        while ((b = inputStream.read(buffer)) != -1) {
            // 4.写到输出流(out)中
            out.write(buffer, 0, b);
        }
        inputStream.close();
        if (out != null) {
            out.flush();
            out.close();
        }

    }

    @PostMapping("insert")
    public BaseResponse testCourse() {
        int n = 0;
        try {
            List<Course> list = new ArrayList<>();
            JsonParser parser = new JsonParser();  //创建JSON解析器
            JsonObject object = (JsonObject) parser.parse(new FileReader("D:\\test.json"));  //创建JsonObject对象
//            System.out.println("cat="+object.get("cat").getAsString()); //将json数据转为为String型的数据
//            System.out.println("pop="+object.get("pop").getAsBoolean()); //将json数据转为为boolean型的数据
            JsonArray array = object.get("course").getAsJsonArray();    //得到为json的数组
            for (int i = 0; i < array.size(); i++) {
                Course course = new Course();
                System.out.println("---------------");
                JsonObject subObject = array.get(i).getAsJsonObject();
                course.setCoursename(subObject.get("name").getAsString());
                course.setCourseid(subObject.get("id").getAsInt());
//                System.out.println("id=" + subObject.get("id").getAsInt());
//                System.out.println("name=" + subObject.get("name").getAsString());
                list.add(course);
            }
            n = courseMapper.batchInsert(list);
            System.out.println(n);
        } catch (JsonIOException e) {
            e.printStackTrace();
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return ResultUtil.getSuccess(n);
    }

    @PostMapping(value = "/file")
    public String file2(MultipartFile file) throws FileNotFoundException, ParseException {
        DemoController de = new DemoController();
        InputStream inputStream = new FileInputStream(de.multipartFileToFile(file));
        ExcelLogs logs = new ExcelLogs();
        Collection<Map> importExcel = ExcelUtil.importExcel(Map.class, inputStream, "yyyy/MM/dd HH:mm:ss", logs, 0);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int count=0;
        for (Map m : importExcel) {
            count++;
            if(count==1){
                continue;
            }
            Person person = new Person();
            person.setName(String.valueOf(m.get("姓名")));
            person.setAge((Integer) m.get("年龄"));
            person.setGender(String.valueOf(m.get("性别")));
            person.setBirthday(sdf.parse(String.valueOf(m.get("出生日期"))));

            log.info(person.toString());
        }
//        File f=new File("src/test/resources/test.xlsx");
//        InputStream inputStream= new FileInputStream(f);
//
//        ExcelLogs logs =new ExcelLogs();
//        Collection<Map> importExcel = ExcelUtil.importExcel(Map.class, inputStream, "yyyy/MM/dd HH:mm:ss", logs , 0);
//
//        for(Map m : importExcel){
//            System.out.println(m);
//        }File f=new File("src/test/resources/test.xlsx");
//        InputStream inputStream= new FileInputStream(f);
//
//        ExcelLogs logs =new ExcelLogs();
//        Collection<Map> importExcel = ExcelUtil.importExcel(Map.class, inputStream, "yyyy/MM/dd HH:mm:ss", logs , 0);
//
//        for(Map m : importExcel){
//            System.out.println(m);
//        }
//    }
        return "succeed";
    }

//    @PostMapping(value = "/test")
//    public static List testImport(MultipartFile file) throws Exception{
//        List<Person> list = ExcelUtil.readXls(file.getBytes(), Person.class);
//        return list;
//    }

    public static File multipartFileToFile(MultipartFile multipartFile) {
        // 获取文件名
        String fileName = multipartFile.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        File excelFile = null;
        try {
            // 用时间作为文件名，防止生成的临时文件重复
            excelFile = File.createTempFile(UUID.randomUUID().toString(), prefix);
            multipartFile.transferTo(excelFile);
        } catch (Exception e) {
            log.error("==========={}文件=================转换异常", fileName);
            e.printStackTrace();
        }
        return excelFile;
    }




}
